trigger UpdateAchieve on ConsumerEducation__c (after update){
    Boolean uaFlag = false;
    Boolean ufFlag = false;
    List<Achieve__c> UpdateList = new List<Achieve__c>();
    List<ID> newCeId = new List<ID>();
    List<Achieve__c> AchList = new List<Achieve__c>();
    for(ConsumerEducation__c t:trigger.new){
        if(trigger.oldmap.get(t.id).arrived_pclass__c != t.arrived_pclass__c){
            uaFlag = true;
        }
        if(trigger.oldmap.get(t.id).firstpurchasevalue__c != t.firstpurchasevalue__c){
            ufFlag = true;
        }
        newCeId.add(t.Hospital__c);
    }
    if((uaFlag == true)||(ufFlag == true)){
        AchList = [Select id,Hospital_Name__c,P_class_cover_actual_calc__c,X1st_Purchase_actual_calc__c,Year__c,Month__c From Achieve__c 
            Where Hospital_Name__c in: newCeId];
        for(ConsumerEducation__c c:trigger.new){
            for(Achieve__c a:AchList){
                Date firstDate =  date.newInstance(integer.valueof(a.Year__c),integer.valueof(a.Month__c),1);
                Date lastDate;
                if(integer.valueof(a.Month__c) == 12){
                    lastDate =  date.newInstance(integer.valueof(a.Year__c),12,31);
                }
                else{
                    lastDate =  date.newInstance(integer.valueof(a.Year__c),integer.valueof(a.Month__c)+1,1) - 1;
                }
                if((a.Hospital_Name__c == c.Hospital__c)&&(c.Date__c >= firstDate)&&(c.Date__c <= lastDate))
                {
                    if(a.P_class_cover_actual_calc__c != null)
                        a.P_class_cover_actual_calc__c = a.P_class_cover_actual_calc__c - trigger.oldmap.get(c.id).arrived_pclass__c
                            + c.arrived_pclass__c;
                    else
                            a.P_class_cover_actual_calc__c = c.arrived_pclass__c;
                    
                    if(a.X1st_Purchase_actual_calc__c != null)
                        a.X1st_Purchase_actual_calc__c = a.X1st_Purchase_actual_calc__c - trigger.oldmap.get(c.id).firstpurchasevalue__c
                            + c.firstpurchasevalue__c;
                    else
                         a.X1st_Purchase_actual_calc__c = c.firstpurchasevalue__c;
                    UpdateList.add(a);
                }
            }    
        }
    }
    if(UpdateList.size() > 0){
        update UpdateList;
    }
}